﻿using System.Diagnostics;

using GCC.Container.Abstracts;

namespace System.APMServer.ProcessWatcher
{
    /// <summary>
    /// OSAPM监测服务
    /// </summary>
    public class OSAPMServer : AbsJobBase
    {
        public OSAPMServer(AbsGCCLogger logger) : base(logger)
        {
            Name = "我是系统OS性能监测服务,单例";
            JobType = GCCJobTypeEnum.Singleton;
            TimerType = GCCJobTimerTypeEnum.Dependent;
        }

        public override Task Start(AbsGCCContext context)
        {

            return Task.Run(async () =>
            {
                using var proc = Process.GetCurrentProcess();
                while (!_cancellToken.Token.IsCancellationRequested)
                {
                    var startTime = DateTime.UtcNow;
                    var startCpuUsage = proc.TotalProcessorTime;

                    await Task.Delay(500);

                    var endTime = DateTime.UtcNow;
                    var endCpuUsage = proc.TotalProcessorTime;

                    var cpuUsedMs = (endCpuUsage - startCpuUsage).TotalMilliseconds;
                    var totalMsPassed = (endTime - startTime).TotalMilliseconds;

                    var cpuUsageTotal = cpuUsedMs / (Environment.ProcessorCount * totalMsPassed);

                    var useAge = cpuUsageTotal * 100;
                    var privateMem = proc.PrivateMemorySize64 / 1024 / 1024;
                    var pagedMem = proc.PagedMemorySize64 / 1024 / 1024;

                    context.SaveTrace("Process", resourceName: "Cpu Age", value: useAge.ToString());
                    context.SaveTrace("Process", resourceName: "Private Memory Size 64", value: $"{privateMem}");
                    context.SaveTrace("Process", resourceName: "Paged Memory Size 64", value: $"{pagedMem}");
                    await Task.Delay((1000 * 20) - 500);

                }

            }, _cancellToken.Token);
        }

        public override Task Stop()
        {
            return Task.Run(() =>
            {
                Logger.Information($"Job {Name} stoping.");
                _cancellToken.Cancel();
                Logger.Information($"Job {Name} stoped.");
            });
        }
    }
}
